package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.MyConfig;
import com.github.wxpay.sdk.WXPay;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:YZN
 * @date:2023/1/7
 * @description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private AddressBookMapper addressBookMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Transactional
    @Override
    public R submit(Orders order) {
        //校验参数
        if (order == null) {
            return R.error("参数错误");
        }
        //创建订单
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(new LambdaQueryWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, BaseContext.getCurrenId()));

        if (shoppingCarts.size() == 0) {
            return R.error("还没点餐,请先点餐");
        }

        User user = userMapper.selectById(BaseContext.getCurrenId());
        AddressBook addressBook = addressBookMapper.selectById(order.getAddressBookId());

        if (addressBook == null) {
            return R.error("此地址不存在");
        }

        order.setNumber(UUID.randomUUID().toString());
        order.setStatus(1);
        order.setUserId(addressBook.getUserId());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setPhone(addressBook.getPhone());

        String address = (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                (addressBook.getDetail() == null ? "" : addressBook.getDetail());
        order.setAddress(address);
        order.setConsignee(addressBook.getConsignee());
        order.setUserName(user.getName());

        BigDecimal bigDecimal = new BigDecimal(0);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            bigDecimal = bigDecimal.add(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber() + "")));
        }
        order.setAmount(bigDecimal);

        orderMapper.insert(order);
        //创建订单详情表
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(s -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getId());
            orderDetail.setName(s.getName());
            orderDetail.setImage(s.getImage());
            orderDetail.setDishId(s.getDishId());
            orderDetail.setSetmealId(s.getSetmealId());
            orderDetail.setDishFlavor(s.getDishFlavor());
            orderDetail.setNumber(s.getNumber());
            orderDetail.setAmount(s.getAmount());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetails.forEach(o -> orderDetailMapper.insert(o));

        //清空购物车
        shoppingCartMapper.delete(new LambdaUpdateWrapper<ShoppingCart>().eq(ShoppingCart::getUserId, BaseContext.getCurrenId()));

        //调用微信统一下单接口
        Map<String, String> wxOrder;
        try {
            wxOrder = createWxOrder(order);
            if (wxOrder.get("return_code").equals("FAIL")) {
                return R.error("服务器异常,请稍后重试");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("服务器异常,请稍后重试");
        }

        return R.success(wxOrder);
    }

    @Override
    public void updateById(String orderId) {
        if (null == orderId) {
            throw new RuntimeException("参数错误");
        }
        Orders orders = new Orders();
        orders.setId(Long.parseLong(orderId));
        orders.setStatus(2);
        orders.setCheckoutTime(LocalDateTime.now());

        orderMapper.updateById(orders);

    }

    @Override
    public Orders getById(String orderId) {
        if (orderId == null) {
            throw new RuntimeException("参数错误");
        }
        return orderMapper.selectById(Long.parseLong(orderId));
    }

    @Override
    public R orderPage(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        //参数校验
        if (page <= 0 || pageSize <= 0) {
            return R.error("参数错误");
        }
        //进行分页查询
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(number),Orders::getNumber,number);
        queryWrapper.le(StringUtils.isNotBlank(endTime),Orders::getOrderTime,endTime);
        queryWrapper.ge(StringUtils.isNotBlank(beginTime),Orders::getOrderTime,beginTime);
        Page<Orders> ordersPage = orderMapper.selectPage(pageInfo, queryWrapper);
        return R.success(ordersPage);
    }

    @Override
    public R userPage(Integer page, Integer pageSize) {
        //参数校验
        if (page <= 0 || pageSize <= 0) {
            return R.error("参数错误");
        }
        //进行分页查询
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        orderMapper.selectPage(pageInfo,null);
        return R.success(pageInfo);
    }

    private Map<String, String> createWxOrder(Orders order) throws Exception {
        MyConfig my = new MyConfig();
        //CONFIG配置类
        WXPay wxPay = new WXPay(my);
        //3.可以进行微信支付接口的调用了
        //统一下单接口
        //4.wxPay.unifiedOrder(); = 调用微信的支付接口  参数map
        Map<String, String> requsetMap = new HashMap<>();

        requsetMap.put("body", "瑞吉外卖");
        requsetMap.put("out_trade_no", order.getId().toString());
        requsetMap.put("total_fee", "1");
        requsetMap.put("spbill_create_ip", "127.0.0.1");
        requsetMap.put("notify_url", "http://54bdf4c.r3.cpolar.top/order/notify");
        requsetMap.put("trade_type", "NATIVE");

        //模拟浏览器发送一个http请求
        /**
         * requsetMap 代表请求参数
         * responseMap  返回值
         */
        Map<String, String> responseMap = wxPay.unifiedOrder(requsetMap);

        responseMap.put("out_trade_no", order.getId().toString());

        return responseMap;

    }
}
